<?php


namespace app\api\controller\customer;

use app\api\controller\Api;
use app\common\customer\model\CustomerAllocate;
use app\common\customer\model\CustomerHotel;
use app\common\system\model\OperateLog;
use think\db\exception\DbException;
use util\Format;

class Hotel extends Api
{
    public function handle()
    {
        $post = $this->request->post();
        if (empty($post['allocate_id'])) return error([], "请选择要分配的客资");
        if (empty($post['user_ids']) && empty($post['hotel_ids'])) return error([], "请选择要分配的员工或酒店");

        // 验证用户权限
        $user = $this->request->user;
        // 获取要分配的客资列表
        $allocateModel = new CustomerAllocate();
        $allocate = $allocateModel->where('id', $post['allocate_id'])->find();
        if (empty($allocate)) return error([], "客资不存在");
        // 获取联系方式
        $allocate->append(['contact']);
        $userIds = [];
        // if (!empty($post['hotel_ids'])) {
        //     $userModel = new \app\common\system\model\User();
        //     $userIds = $userModel->whereIn('store_id', $post['hotel_ids'])->column('id');
        // }

        // 记录分配结果
        $success = $failed = [];
        $notices = [];
        $userIds = array_merge($userIds, $post['user_ids']);
        $userIds = array_unique($userIds);
        $Message = new \app\common\third\Message();
        foreach ($userIds as $userId) {
            // 分配数据到用户
            $where = [];
            $where[] = ['member_id', '=', $allocate->member_id];
            $where[] = ['user_id', '=', $userId];
            // 检测是否已经分配过
            $hadAllocate = $allocateModel->where($where)->find();

            if (!empty($hadAllocate) && ($hadAllocate['status'] == 7 || $hadAllocate['status'] == 6)) {
                // 失效的重新跟进
                $hadAllocate->save(['status' => 1, 'operate_id' => $user['id'], 'create_time' => time()]);
                $contact = Format::mobile($allocate->contact['contact']);
                $notice['content'] = $Message->buildCustomerMessage($user, $userId, ['id' => $hadAllocate->id, 'contact' => $contact]);
                $notice['options'] = ['allocate_id' => $hadAllocate->id];
                array_push($notices, $notice);
                array_push($success, $hadAllocate->toArray());
                continue;
            }

            // 分配数据
            $data = [];
            $data['member_id'] = $allocate->member_id;
            $data['create_id'] = $allocate->create_id;
            $data['from_user_id'] = $user['id'];
            $data['operate_id'] = $user['id'];
            $data['user_id'] = $userId;
            $data['assign_type'] = 3;
            // 提醒数据
            $notice = [];
            $notice['from_user_id'] = $user['id'];
            $notice['user_id'] = $userId;
            $notice['type'] = 1;
            try {
                $allocateModel = new CustomerAllocate();
                $allocateModel->save($data);
                array_push($success, $data);
                $allocate->save(['assign_status' => 1]);

                $contact = Format::mobile($allocate->contact['contact']);
                // 提醒数据
                $notice['content'] = $Message->buildCustomerMessage($user, $userId, ['id' => $allocateModel->id, 'contact' => $contact]);
                $notice['options'] = ['allocate_id' => $allocateModel->id];
                array_push($notices, $notice);
            } catch (DbException $e) {
                \think\facade\Log::write($e->getMessage());
                array_push($failed, $data);
            }
        }

        $storeIds = [];
        if (!empty($userIds)) {
            $userModel = new \app\common\system\model\User();
            $storeIds = $userModel->whereIn('id', $userIds)->column('store_id');
        }
        $storeIds = array_filter($storeIds);
        $hotelIds = array_merge($storeIds, $post['hotel_ids']);
        foreach ($hotelIds as $hotelId) {
            $data = [];
            $data['allocate_id'] = $allocate->id;
            $data['member_id'] = $allocate->member_id;
            $data['hotel_id'] = $hotelId;
            $data['from_user_id'] = $user['id'];
            $data['status'] = $allocate['status'];
            try {
                $toHotelModel = new CustomerHotel();
                $toHotelModel->save($data);
            } catch (DbException $e) {
            }
        }


        $result['success'] = count($success);
        $result['failed'] = count($failed);
        // 发送提醒
        if (!empty($notices)) {
            $noticeModel = new \app\common\system\model\Notice();
            $noticeModel->saveAll($notices);
        }

        // 核销表单token
        // $formLogic = new FormLogic();
        // $formLogic->removeToken($post['form_token']);
        // $res = "分配成功" . count($success) . "个，失败" . count($failed) . "个";
        return success($result, "操作完成");
    }

    public function update()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        $model = new CustomerHotel();
        $row = $model->where('id', $post['id'])->find();

        try {
            $origin = $row->getData();
            $row->save(['status' => $post['status']]);
            $changed = $row->getData();
            $modelName = CustomerHotel::class;

            OperateLog::write($user['id'], $row['member_id'], $origin, $changed, $modelName, 1);
        } catch (DbException $e) {
            return error([], $e->getMessage());
        }

        return success([], "更新成功");
    }

    public function delete()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        $model = new CustomerHotel();
        $row = $model->where('id', $post['id'])->find();
        $origin = $row->getData();

        try {
            $row->delete();
            $changed = $row->getData();
            $modelName = CustomerHotel::class;

            OperateLog::write($user['id'], $row['member_id'], $origin, $changed, $modelName, 1);
        } catch (DbException $e) {
            return error([], $e->getMessage());
        }

        return  success([], "删除成功");
    }
}